package es.ibm.santillana.mdm.entryPreview.catalog;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ccd.common.context.AustinContext;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.OrderedJSONObject;
import com.ibm.pim.attribute.AttributeInstance;
import com.ibm.pim.catalog.Catalog;
import com.ibm.pim.catalog.CatalogManager;
import com.ibm.pim.catalog.item.Item;
import com.ibm.pim.context.Context;
import com.ibm.pim.context.PIMContextFactory;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;
import com.ibm.pim.web.framework.dispatcher.AsyncEnabled;
import com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled;

import es.ibm.santillana.mdm.common.util.ConstSantillana;

public class VisorPacks implements AsyncEnabled,RequestResponseEnabled{
	
	private static String sSpecName = "Articulos CPS";
	HttpServletRequest request;
	HttpServletResponse response;
	Context ctxPIM;
	CatalogManager ctgMan;
	Catalog catalogoMaestro;
	
	//send an json array
	String responseContent ="";

	/* (sin Javadoc) 
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getContentType()
	 */
	public String getContentType() {
		
		return JSON;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getResponseContent()
	 */
	public String getResponseContent() {
		
		return responseContent;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setResponse(javax.servlet.http.HttpServletResponse)
	 */
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	/**
	 * FlowConfig Method.
	 */
	public void inicializaPacks(){
		ctxPIM = PIMContextFactory.getCurrentContext();
		ctgMan = ctxPIM.getCatalogManager();
		
	}
	
	/**
	 * FlowConfig Method.
	 * @throws IOException 
	 */
	public void obtenerDatos() throws IOException{
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);
		String sPk = request.getParameter("PK");
		String sUrl = request.getParameter("URL");
		String sbWf = request.getParameter("URL");
		String sCtgName = request.getParameter("URL");
		System.out.println("Request URI: "+ request.getRequestURI());
		System.out.println("Remote Addr: "+ request.getRemoteAddr());
		JSONArray aListOrden = obtenerInfoPack(sPk,sUrl);
		responseContent = aListOrden.serialize(true);
		
	}
	
	private Boolean isPack(Item item){
		AttributeInstance attInstancePacks =  item.getAttributeInstance(sSpecName + "/Packs");
		if(attInstancePacks!=null){
			List<AttributeInstance> packs = (List<AttributeInstance>) attInstancePacks.getChildren();
			if(packs!=null && packs.size()>0){
				return true;
			}
		}
		return false;
	}
	
	//http://10.125.143.100:7507/Prueba.wpc?PK=34554135&User=Admin&Padre=true&Titulo=Asignaturas
	
	private String cambiarIP(String pkFinal, String tituloFinal, String urlOriginal){
		int separaIP = urlOriginal.indexOf(".wpc?PK");
		int separa1 = urlOriginal.indexOf("&User=");
		int separa2 = urlOriginal.indexOf("&Padre=");
		return urlOriginal.substring(0, separaIP + 8) + pkFinal + urlOriginal.substring(separa1, separa2) + "&Padre=false&Titulo=" + tituloFinal;
	}
	
	private String createLink(String sPk,String url, String titulo){
		if(catalogoMaestro==null){
			if(ctgMan==null){
				if(ctxPIM==null){
					ctxPIM = PIMContextFactory.getCurrentContext();
				}
				ctgMan = ctxPIM.getCatalogManager();
			}
			catalogoMaestro = ctgMan.getCatalog("Maestro Articulos");
		}
		Item item = catalogoMaestro.getItemByPrimaryKey(sPk);
		if(isPack(item)){
			return "<A href=\"" + cambiarIP(sPk,titulo,url) + "\" title=\"Ir al Pack.\">" + sPk + "</A>";
		}
		else{
			return "No";
		}
	}
	
	private String createImageLink(String sPk){
		if(catalogoMaestro==null){
			if(ctgMan==null){
				if(ctxPIM==null){
					ctxPIM = PIMContextFactory.getCurrentContext();
				}
				ctgMan = ctxPIM.getCatalogManager();
			}
			catalogoMaestro = ctgMan.getCatalog("Maestro Articulos");
		}
		Item item = catalogoMaestro.getItemByPrimaryKey(sPk);
		AttributeInstance atiImagen = item.getAttributeInstance(sSpecName + "/ImagenLibro");
		if(atiImagen!=null){
			
		}
		String link = (String) item.getAttributeValue(sSpecName + "/ImagenLibro");
		if(link!=null){
			
			LookupTableManager lkpMan = PIMContextFactory.getCurrentContext().getLookupTableManager();
			LookupTable lkp =  lkpMan.getLookupTable(ConstSantillana.LOOKUP_SYSTEM);
			LookupTableEntry lkpEntry = lkp.getLookupTableEntry("company");
			String sCompany = (String) lkpEntry.getAttributeValue("Code_Value_LTS/Value");
			
			return "<img src=\"/suppliers/"+sCompany+"/ctg_files/"+ link+"\" alt=\"Imagen del articulo.\" width=\"60\" height=\"80\">";
		}
		else{
			return "";
		}
	}
	
	private JSONArray obtenerInfoPack(String sPk,String sURL){
		JSONArray aListOrden = new JSONArray();
		if(ctxPIM==null){
			ctxPIM = PIMContextFactory.getCurrentContext();
		}
		if(ctgMan==null){
			ctgMan = ctxPIM.getCatalogManager();
		}
		
		Catalog catalogo = ctgMan.getCatalog("Maestro Articulos");
		Item item = catalogo.getItemByPrimaryKey(sPk);
		AttributeInstance attInstancePacks =  item.getAttributeInstance(sSpecName + "/Packs");
		List<AttributeInstance> packs = null;
		if(attInstancePacks!=null){
			packs = (List<AttributeInstance>) attInstancePacks.getChildren();
		
			if(packs!=null && packs.size()>0){
				for(AttributeInstance attInstanceTemp : packs){
					OrderedJSONObject obj = new OrderedJSONObject();
				//	Item itemRelacionado = attInstanceTemp.getPath();	
					System.out.println( attInstanceTemp.getPath());
					String sPkitemRelacionado = (String) item.getAttributeValue(attInstanceTemp.getPath() + "/ArticuloRelacionado");
					Item itemRelacionado = catalogo.getItemByPrimaryKey(sPkitemRelacionado);
					String tituloRelacionado = (String) itemRelacionado.getAttributeValue(sSpecName + "/General/TituloCorto");
					String isbnRelacionado = (String) itemRelacionado.getAttributeValue(sSpecName + "/Control/ISBN");
					Integer numeroArticulos = (Integer) item.getAttributeValue(attInstanceTemp.getPath() + "/NumeroArticulos");
					Integer orden = (Integer) item.getAttributeValue(attInstanceTemp.getPath() + "/Orden");
					obj.put("Orden", orden.toString());
					obj.put("Titulo", tituloRelacionado);
					obj.put("ISBN", isbnRelacionado);
					obj.put("Numero",numeroArticulos.toString());
					obj.put("Imagen", createImageLink(sPkitemRelacionado));
					//obj.put("Link","http://10.125.142.114:7507/Prueba.wpc?PK=" +sPkitemRelacionado +"&User=Admin");
					obj.put("Link",createLink(sPkitemRelacionado,sURL,tituloRelacionado));
					aListOrden.add(obj);
					System.out.println("Item: " + sPkitemRelacionado + " numero: " + numeroArticulos + " orden: " + orden);
					
				}
		
			}
		}
		return aListOrden;
	}
	
}
